<template>
  <div class="app-container course-add course width-label schoolFeedBack">
    <div class="edit-title-line">基本信息</div>
    <el-form ref="feedBackForm" :model="feedBackForm" :rules="FeedBackFormRules" >
      <div >
        <el-form-item label="标题：" class="normal-form-item" prop="title" >
          <el-input v-model="feedBackForm.title"
                    class="width-300" size="small"
                    maxlength="30"
                    show-word-limit
                    ref="title"
                    @focus="clearFormValidate('title')"
          ></el-input>
        </el-form-item>
      </div>
      <el-form-item label="学期：" class="normal-form-item"  prop="semesterCode">
        <el-select v-model="feedBackForm.semesterCode"
                   placeholder="请选择" class="width-300"
                   size="small"
                   @change="handleChangeSemester"
                   clearable >
          <el-option
            v-for="item in schoolSemesterList"
            :key="item.code"
            :label="item.label"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>
      <div>
        <el-form-item label="学科：" class="normal-form-item" prop="subjectType">
          <el-select v-model="feedBackForm.subjectType" @change="handleSubjectChange" placeholder="请选择" class="width-300"  size="small"  clearable >
            <el-option
              v-for="item in subjectTypeData"
              :key="item.subjectId"
              :label="item.subjectName"
              :value="item.subjectId">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
      <el-form-item label="年级：" class="normal-form-item" prop="gradeType">
        <el-select v-model="feedBackForm.gradeType" placeholder="请选择"
                   class="width-300" @change="handleGradeChange" size="small" clearable >
          <el-option
            v-for="(item, index) in gradeTypeData"
            :key="index"
            :label="item.name"
            :value="item.distanceYear">
          </el-option>
        </el-select>
      </el-form-item>

      <div class="feedback-special-form-item" >
        <el-form-item label="反馈给谁：" class="normal-form-item" prop="toFeedBack">
          <el-select multiple v-model="feedBackForm.toFeedBack" placeholder="请选择"
                     filterable
                     class="width-500" @change="handleToFeedBackChange" size="small" clearable >
            <el-option
              v-for="item in toFeedBackList"
              :key="item.staffId"
              :label="item.name"
              :value="item.staffId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-checkbox-group v-model="feedBackForm.sendToWx">
          <el-checkbox label="添加成功后发送微信消息" name="type"></el-checkbox>
        </el-checkbox-group>
      </div>

      <div>
        <el-form-item label="检查内容：" class="normal-form-item" prop="checkContent" >
          <el-input v-model="feedBackForm.checkContent"
                    type="textarea"
                    class="width-500"
                    size="small"
                    maxlength="50"
                    :autosize="checkContentAutosize"
                    show-word-limit
                    @focus="clearFormValidate('checkContent')"
          ></el-input>
        </el-form-item>
      </div>

      <div>
        <el-form-item label="关联备课：" class="normal-form-item" >
          <el-select v-model="feedBackForm.associationCourse" placeholder="请选择"
                     class="width-500"  multiple size="small" clearable >
            <el-option
              v-for="item in associationCourseList"
              :key="item.lessonId"
              :label="item.lessonName"
              :value="item.lessonId">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="edit-title-line">整体情况</div>
      <div>
        <editor-bar v-model="overallSituation.editor" :height="600"  ></editor-bar>
      </div>
      <div class="edit-title-line">整改建议</div>
      <div>
        <editor-bar v-model="overAllAdvice.editor" :height="600" ></editor-bar>
      </div>
      <div style="margin-top: 20px">
        <el-form-item>
          <el-button type="primary" style="margin-right: 20px" @click="feedBackFormSubConfirm">保存</el-button>
          <el-button @click="cancelConfirm=true">取消</el-button>
        </el-form-item>
      </div>
    </el-form>
    <el-confirm-dialog
      elTip="确定要取消吗，若取消当前信息将不会保存？"
      :showDialog="cancelConfirm"
      :confirmSubmit="elConfirmDialogSubmit"
      :confirmCancel="elConfirmDialogCancel"
      @closeDialog = "elConfirmDialogClose"
    >
    </el-confirm-dialog>
  </div>
</template>


<script>
  import ElConfirmDialog from '@/components/ElConfirmDialog/index.vue'
  import EditorBar from '@/components/Tinymce'
  import  {getFeedbackDetail, saveOrUpdateFeedback, getLessonListByAuthor,
    getStaffList, getSubjectList, getSchoolGradeList, getSchoolSemesterList, getLessonListByLessonIds } from '@/api/api.js'
  export default {
    name: "edit",
    components: {
      ElConfirmDialog,
      EditorBar
    },
    data() {
      return {
        fileUploadUrl: 'http://www.baidu.com',
        //文件上传类型
        acceptFileType: ".xls, .xlsx, .ppt, .pptx, .doc, .docx, image/*",
        fileType: [
          'gif',
          'jpeg',
          'jpg',
          'bmp',
          'png',
          'ppt',
          'pptx',
          'doc',
          'docx',
        ],
        //当前学科
        currentSubject: {
          subjectId: '',
          subjectName : '',
          subjectCode : '',
          subjectType : '',
          subjectLevel : '',
        },
        // 当前学年
        currentSemester: {
          semesterId : '',
          schoolYear : '',
          term: '',
        },
        //当前年级
        currentGrade: {
          gradeName: '',
          distanceYear: '',
        },
        schoolSemesterList : [],
        //班级列表
        classData: [],
        //班级全选
        checkAllClass: false,
        isIndeterminate: true,
        checkContentAutosize: { minRows: 4, maxRows: 10 },
        //年级类型
        gradeTypeData: [],
        // 学科类型
        subjectTypeData: [],
        //反馈接收人列表
        toFeedBackList: [],
        //
        //关联备课列表
        associationCourseList: [],
        //备课类型
        courseTypeData: [  ],
        feedBackForm: {
          id : '',
          title: '',
          semesterCode : '',
          checkContent : '',
          subjectId : '',
          subjectName : '',
          subjectCode : '',
          subjectType: '',
          courseType: '',
          subjectLevel : '',
          distanceYear : '',
          gradeType: '',
          gradeName :'',
          overallSituation : '',
          repairSuggession : '',
          fbToUserIdString : '',
          lessonString : '',
          toFeedBack: [],
          associationCourse: [], //关联备课
          sendToWx: false,
        },
        FeedBackFormRules: {
          title : [
            { required: true, message: '必填项，请填写！', trigger: 'blur' },
            { max: 30, message: '最多 30 个字符', trigger: 'blur' }
          ],
          courseType: [
            { required: true, message: '必填项，请填写！', trigger: 'change' }
          ],
          subjectType : [
            { required: true, message: '必填项，请填写！', trigger: 'change' }
          ],
          gradeType : [
            { required: true, message: '必填项，请填写！', trigger: 'change' }
          ],
          semesterCode : [
            { required: true, message: '必填项，请填写！', trigger: 'change' }
          ],
          classData: [
            { required: true, message: '必填项，请填写！', trigger: 'change' }
          ],
          toFeedBack: [
            { required: true, message: '必填项，请填写！', trigger: 'change' }
          ],
          checkContent: [
            { required: true, message: '必填项，请填写！', trigger: 'blur' },
            { max: 50, message: '最多 50 个字符', trigger: 'blur' }
          ]
        },
        // 文件上传列表
        uploadFileList: [],

        //询问框
        cancelConfirm: false,
        checkContentAutoSize: { minRows: 4, maxRows: 10 },
        //富文本编辑框
        overallSituation:{
          editor: '',
          isClear: false
        },
        overAllAdvice: {
          editor: '',
          isClear: false,
        }
        //富文本编辑框结束
      }
    },
    methods: {

      // 班级checkBox变化
      //年级变化获取对应的班级
      handleGradeChange() {
        let tempGrade = this.getGradeMsgByDistanceYear(this.feedBackForm.gradeType);
        if (tempGrade == null) {
          return ;
        }
        this.currentGrade.distanceYear = tempGrade.distanceYear;
        this.currentGrade.gradeName = tempGrade.name;
      },


      /** 取消询问框相关**/
      elConfirmDialogSubmit() {
        this.cancelConfirm = false
        // this.initAddCourseForm()
        this.$router.push("/schoolFeedBack/list")
      },
      elConfirmDialogCancel() {
        this.cancelConfirm = false
      },
      elConfirmDialogClose() {
        this.cancelConfirm = false
      },
      /** 表单提交相关 **/
      //表单初始化
      initAddCourseForm() {
        //缺少富文本字段
        this.feedBackForm = {
          id : '',
          title: '',
          checkContent : '',
          subjectId : '',
          subjectName : '',
          subjectCode : '',
          subjectType: '',
          courseType: '',
          subjectLevel : '',
          subjectType: '',
          distanceYear : '',
          gradeName :'',
          overallSituation : '',
          repairSuggession : '',
          gradeType: '',
        }
      },
      initSchoolFeedBackById(feedbackId) {
        let params = {
          feedbackId
        }
        getFeedbackDetail(params).then(res => {
          if (res.code == 200) {
              this.feedBackForm.id = res.result.id
              this.feedBackForm.title = res.result.title

              this.feedBackForm.semesterCode = `${res.result.schoolYear}${res.result.term}`
              //获取学年信息
              this.initCurrentSemesterBySemestrId(res.result.semesterId)
              this.initCurrentSubject(res.result.subjectId)
              this.initCurrentGrade(res.result.distanceYear)
              this.feedBackForm.subjectType = res.result.subjectId
              this.feedBackForm.gradeType = res.result.distanceYear
              this.feedBackForm.toFeedBack =res.result.fbToUserIdString != null  ?  res.result.fbToUserIdString.split(",") : []
              this.feedBackForm.checkContent = res.result.checkContent
              this.feedBackForm.associationCourse = res.result.lessonString ?  res.result.lessonString.split(",") : []
              this.overallSituation.editor = res.result.overallSituation ||  null
              this.overAllAdvice.editor = res.result.repairSuggession || null
              this.handleToFeedBackChange()
          } else {
            this.$alert("获取反馈详情失败！" + res.message, "错误", {type : "error"})
          }
        })
      },
      /**富文本编辑框**/
      overAllAdviceEditorOnfocus() {

      },
      JSONStringifyLesson(lessonIdArr){
        if( !lessonIdArr || !Array.isArray(lessonIdArr) || lessonIdArr.length <= 0) {
          return null;
        }
        let lessonResArr = []
        lessonIdArr.forEach(item => {
          for (let lesson of this.associationCourseList) {
            if (lesson.lessonId == item) {
              let tempLesson = {
                lessonId : lesson.lessonId,
                lessonName : lesson.lessonName
              }
              lessonResArr.push(tempLesson);
              continue ;
            }
          }
        })
        return JSON.stringify(lessonResArr)
      },

      feedBackFormSubConfirm() {
        this.$refs.feedBackForm.validate(valid => {
          if (valid) {
            let params = {
              id : this.feedBackForm.id,
              title : this.feedBackForm.title,
              checkContent : this.feedBackForm.checkContent,
              subjectId : this.currentSubject.subjectId,
              subjectName : this.currentSubject.subjectName,
              subjectCode : this.currentSubject.subjectCode,
              subjectType : this.currentSubject.subjectType,
              subjectLevel :this.currentSubject.subjectLevel,
              semesterId : this.currentSemester.semesterId,
              schoolYear : this.currentSemester.schoolYear,
              term : this.currentSemester.term,
              distanceYear : this.currentGrade.distanceYear,
              gradeName : this.currentGrade.gradeName,
              overallSituation : this.overallSituation.editor,
              repairSuggession : this.overAllAdvice.editor,
              fbToUserIdString : this.feedBackForm.toFeedBack.join(","),
              lessonString : this.JSONStringifyLesson(this.feedBackForm.associationCourse),
              sendToWx : this.feedBackForm.sendToWx,
            }
            saveOrUpdateFeedback(params).then(res => {
              if (res.code === 200) {
                this.$alert("保存成功！", "提示", {type : "success",
                  callback : () => {
                    this.$router.push({path : "/schoolFeedBack/list"})
                  }
                })
              } else {
                this.$alert("保存失败！" + res.message, "错误", {type : "error"})
              }
            })
          } else {
            this.$alert("输入有误，请检查", "提示", {type : "warning"})
          }
        })
      },
      /**富文本编辑框结束**/
      /**清除校验**/
      clearFormValidate(prop) {
        this.$refs.feedBackForm.clearValidate(prop)
      },

      handleToFeedBackChange() {
        let createByIdArr = this.feedBackForm.toFeedBack
        let params = {
          createByList : createByIdArr.join(",")
        }
        getLessonListByAuthor(params).then(res => {
          if (res.code == 200) {
            this.associationCourseList = (res.result && Array.isArray(res.result)) ? res.result : []
          } else {
            this.$alert("获取关联备课失败！" + res.message, "错误", {type : "error"})
          }
        })
      },

      /**初始化**/
      initSubjectList() {
        let params = {
        }
        getSubjectList(params).then(res => {
          if(res.code == 200) {
            this.subjectTypeData = this.formatSubjectList(res.result)
            this.initSchoolSemester()
          } else {
            this.$alert("获取学科数据失败！" + res.message, "错误", {type : "error"})
          }
        })
      },
      // 格式化科目信息
      formatSubjectList(array) {
        if(!array || !Array.isArray(array) || array.length <= 0) {
          this.$alert('学校还未维护学科选项信息，请联系华育技术支持进行初始化！', '提示', {
            confirmButtonText: '我知道了',
          });
          return []
        }
        let tempArr = []
        array.forEach(item => {
          let tempItem = {
            subjectId: item.id,
            subjectName : item.name,
            subjectCode : item.code,
            subjectType : item.type,
            subjectLevel :  item.level
          }
          tempArr.push(tempItem)
        })
        return tempArr
      },
      handleChangeSemester() {
        if (!this.feedBackForm.semesterCode || this.schoolSemesterList.length < 0){
          return null
        }
        for (let item of this.schoolSemesterList) {
          if (item.code == this.feedBackForm.semesterCode) {
            if (item.code.length >= 5) {
              this.currentSemester.semesterId = item.semesterId
              this.currentSemester.schoolYear = item.code.substr(0, 4)
              this.currentSemester.term = item.code.substr(4, 1)
              break;
            }
          }
        }
      },
      initCurrentSemesterBySemestrId(semesterId) {
        if (!semesterId) {
          return
        }

        for (let item of this.schoolSemesterList) {
          if (item.semesterId == semesterId) {
            this.currentSemester.semesterId = semesterId
            this.currentSemester.schoolYear = item.code.substr(0, 4)
            this.currentSemester.term = item.code.substr(4, 1)
            break;
          }

        }

      },
      //学科变化获取当前学科详情
      handleSubjectChange() {
        if (!this.feedBackForm.subjectType || this.subjectTypeData.length <= 0) {
          return null;
        }
        for (let item of this.subjectTypeData) {
          if (item.subjectId == this.feedBackForm.subjectType) {
            this.currentSubject = item
            break;
          }
        }
      },
      initSchoolSemester() {
        getSchoolSemesterList().then(res => {
          if ( res.code == 200) {
            if (res.result && Array.isArray(res.result) && res.result.length > 0) {
              let tempSemesterList  = res.result
              tempSemesterList.forEach(semesterItem => {
                let year = parseInt(semesterItem.schoolYear) + parseInt(1)
                let term = semesterItem.term == 1 ? "第一学期" : "第二学期"
                let label   =  `${parseInt(semesterItem.schoolYear)}年-${year}年${term}`
                let code = `${semesterItem.schoolYear}${semesterItem.term}`
                let semesterId = semesterItem.id
                this.schoolSemesterList.push({label, code, semesterId})
              })
              this.initGradeList()
            } else {
              this.$alert('学校还未维护学年学期信息，请联系华育技术支持进行添加！', '提示', {
                confirmButtonText: '我知道了',
              });
            }
          } else {
            this.$alert("获取学年学期数据失败！" + res.message, "错误", {type: "error"})
          }
        })
      },
      initCurrentGrade(distanceYear) {
        if (  this.gradeTypeData.length <= 0) {
          return
        }
        for (let item of this.gradeTypeData) {
          if (item.distanceYear == distanceYear) {
            this.currentGrade.distanceYear = item.distanceYear
            this.currentGrade.gradeName = item.name
            break;
          }
        }
      },
      //初始化当前学科信息
      initCurrentSubject(subjectId) {
        if (!subjectId || this.subjectTypeData.length <= 0) {
          return null;
        }
        for (let item of this.subjectTypeData) {
          if(item.subjectId == subjectId) {
            this.currentSubject.subjectId = item.subjectId
            this.currentSubject.subjectLevel = item.subjectLevel
            this.currentSubject.subjectType = item.subjectType
            this.currentSubject.subjectCode = item.subjectCode
            this.currentSubject.subjectName = item.subjectName
            break;
          }
        }
      },
      initGradeList() {
        this.gradeTypeData= []
        getSchoolGradeList().then(res => {
          if (res.code === 200) {
            if (res.result && res.result.length && res.result.length > 0) {
              this.gradeTypeData = res.result;
              this.initStaffList()
            } else {
              this.$alert('学校还未维护年级选项信息，请联系华育技术支持进行初始化！', '提示', {
                confirmButtonText: '我知道了',
              });
            }
          } else {
            this.$alert("获取年级选项列表失败！" + res.message, "错误", {type : "error"})
          }
        })
      },
      //根据distanceYear获取学年详情
      getGradeMsgByDistanceYear(distanceYear) {
        if (this.gradeTypeData && this.gradeTypeData.length && this.gradeTypeData.length > 0) {
          for (let item of this.gradeTypeData) {
            if (item.distanceYear == distanceYear) {
              return item;
            }
          }
        }
        return null;
      },
      initStaffList() {
        this.toFeedBackList = []
        getStaffList().then(res => {
          if (res.code === 200) {
            if (res.result && res.result.length && res.result.length > 0) {
              this.toFeedBackList = res.result;
              this.initSchoolFeedBackById(this.feedBackForm.id)
            } else {
              this.$alert('学校还未维护教职工信息，请进行初始化！', '提示', {
                confirmButtonText: '我知道了',
              });
            }
          } else {
            this.$alert("获取年级选项列表失败！" + res.message, "错误", {type : "error"})
          }
        })
      },
      initFeedbackTo(userIdString) {
        if (!userIdString) {
          return ;
        }
        let userIdArr =  userIdString.split(",");
        this.feedBackForm.toFeedBack = userIdString.split(",")
        this.toFeedBackList.forEach(item => {

        })
      },
      /** 初始化结束 **/

    },
    created() {
      this.feedBackForm.id  = this.$route.query.feedBackId
    },
    mounted() {
      this.$refs.feedBackForm.clearValidate();
      this.initSubjectList()
      this.$refs.title.focus()
    }
  }
</script>


<style scoped>

</style>
